import request, { ApiResponse } from './request'

// 用户相关接口类型
export interface User {
  id: number
  username: string
  email: string
  avatar?: string
  role: string
  createdAt: string
  updatedAt: string
}

export interface LoginParams {
  username: string
  password: string
}

export interface LoginResponse {
  token: string
  user: User
  refreshToken?: string
}

export interface RegisterParams {
  username: string
  email: string
  password: string
  confirmPassword: string
}

export interface ManagedUserDTO {
  _id?: string
  id?: number
  username: string
  displayName?: string
  roleName?: string
  email?: string
  phone?: string
  department?: string
  status?: 'active' | 'invited' | 'suspended'
  lastLoginAt?: string
  riskLevel?: 'low' | 'medium' | 'high'
  createdAt?: string
  updatedAt?: string
}

export interface ManagedUserListResponse {
  list: ManagedUserDTO[]
  total: number
  page: number
  limit: number
  totalPages: number
  pageSize?: number
}

export interface UpdateManagedUserPayload {
  roleName?: string
  status?: 'active' | 'invited' | 'suspended'
  department?: string
  riskLevel?: 'low' | 'medium' | 'high'
}

const createMockManagedUsers = (): ManagedUserDTO[] => [
  {
    _id: 'U-10001',
    username: 'sophia.chen',
    displayName: '陈悦',
    roleName: 'super-admin',
    email: 'sophia.chen@example.com',
    phone: '138****1201',
    department: '平台运营部',
    status: 'active',
    lastLoginAt: '2025-06-01T08:35:00+08:00',
    riskLevel: 'low',
  },
  {
    _id: 'U-10002',
    username: 'liam.wu',
    displayName: '吴天',
    roleName: 'operator',
    email: 'liam.wu@example.com',
    phone: '139****2314',
    department: '品牌招商中心',
    status: 'active',
    lastLoginAt: '2025-06-01T09:12:00+08:00',
    riskLevel: 'medium',
  },
  {
    _id: 'U-10003',
    username: 'ava.zhang',
    displayName: '张珺',
    roleName: 'auditor',
    email: 'ava.zhang@example.com',
    phone: '136****4521',
    department: '风控审计部',
    status: 'active',
    lastLoginAt: '2025-06-01T07:58:00+08:00',
    riskLevel: 'low',
  },
  {
    _id: 'U-10004',
    username: 'ethan.liu',
    displayName: '刘启航',
    roleName: 'manager',
    email: 'ethan.liu@example.com',
    phone: '137****8890',
    department: '渠道拓展组',
    status: 'invited',
    lastLoginAt: '',
    riskLevel: 'low',
  },
  {
    _id: 'U-10005',
    username: 'mia.sun',
    displayName: '孙芷怡',
    roleName: 'operator',
    email: 'mia.sun@example.com',
    phone: '135****6688',
    department: '活动策划组',
    status: 'active',
    lastLoginAt: '2025-05-31T22:14:00+08:00',
    riskLevel: 'low',
  },
  {
    _id: 'U-10006',
    username: 'jack.han',
    displayName: '韩博文',
    roleName: 'operator',
    email: 'jack.han@example.com',
    phone: '139****7788',
    department: '客服质检组',
    status: 'suspended',
    lastLoginAt: '2025-05-15T15:20:00+08:00',
    riskLevel: 'high',
  },
  {
    _id: 'U-10007',
    username: 'olivia.ma',
    displayName: '马清清',
    roleName: 'manager',
    email: 'olivia.ma@example.com',
    phone: '188****1123',
    department: '会员运营中心',
    status: 'active',
    lastLoginAt: '2025-06-01T06:45:00+08:00',
    riskLevel: 'medium',
  },
  {
    _id: 'U-10008',
    username: 'noah.jiang',
    displayName: '姜晨曦',
    roleName: 'auditor',
    email: 'noah.jiang@example.com',
    phone: '159****3344',
    department: '数据合规组',
    status: 'invited',
    lastLoginAt: '',
    riskLevel: 'low',
  },
]

const mockManagedUsers = createMockManagedUsers()

const asyncDelay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

const buildRoleHeaders = () => {
  if (typeof window === 'undefined') {
    return {}
  }
  try {
    const raw = window.localStorage.getItem('user_info')
    if (!raw) return {}
    const parsed = JSON.parse(raw) as { roleKey?: string; roleName?: string }
    let role = (parsed.roleKey || parsed.roleName || '').toString().trim()
    if (!role) return {}

    if (role === '超级管理员') {
      role = 'super-admin'
    } else if (role.toLowerCase() === 'super_admin') {
      role = 'super-admin'
    }

    return { 'x-user-role': role }
  } catch (error) {
    console.warn('[userAPI] 解析用户信息失败', error)
    return {}
  }
}

// 分页参数
export interface PaginationParams {
  page?: number
  pageSize?: number
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
}

// 分页响应
export interface PaginationResponse<T> {
  list: T[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

export interface AuditLogOperatorSummary {
  operatorId?: string
  operatorName?: string
  operatorAccount?: string
  operatorRole?: string
}

export interface AuditLogRecord {
  _id: string
  module?: string
  operationType: string
  operationTime: string
  operatorId?: string
  operatorAccount?: string
  operatorName?: string
  operatorRole?: string
  viewerScope?: string[]
  targetType?: string
  targetId?: string
  targetName?: string
  ipAddress?: string
  userAgent?: string
  location?: string
  beforeData?: Record<string, unknown> | null
  afterData?: Record<string, unknown> | null
  diffFields?: string[]
  resultStatus: 'success' | 'failure'
  resultMessage?: string
  durationMs?: number
  riskLevel?: 'low' | 'medium' | 'high'
  riskReason?: string
  correlationId?: string
  chainId?: string
  tags?: string[]
  metadata?: Record<string, unknown> | null
  isRead: boolean
  isAbnormal: boolean
  alertChannels?: string[]
  acknowledgedBy?: string
  acknowledgedAt?: string
  createdAt: string
  updatedAt: string
}

export interface AuditLogAggregates {
  modules: string[]
  operators: AuditLogOperatorSummary[]
  targetTypes: string[]
  operationTypes: string[]
  riskLevels: Array<'low' | 'medium' | 'high'>
}

export interface AuditLogCounters {
  unreadCount: number
  abnormalCount: number
  unprocessedAbnormalCount: number
}

export interface AuditLogListResponse {
  list: AuditLogRecord[]
  total: number
  page: number
  limit: number
  totalPages: number
  aggregates: AuditLogAggregates
  counters: AuditLogCounters
}

export interface AuditLogDailyTrendItem {
  date: string
  total: number
  success: number
  failure: number
  highRisk: number
}

export interface AuditModuleStat {
  module: string
  count: number
  highRisk: number
}

export interface AuditOperationStat {
  operationType: string
  count: number
  failure: number
}

export interface AuditHeatmapCell {
  dayOfWeek: number
  hour: number
  riskLevel: 'low' | 'medium' | 'high'
  count: number
}

export interface AuditCorrelationStep {
  operationTime: string
  operatorName?: string
  operationType: string
  targetName?: string
  resultStatus: 'success' | 'failure'
  riskLevel?: 'low' | 'medium' | 'high'
}

export interface AuditCorrelationChain {
  chainId: string
  targetType?: string
  targetName?: string
  module?: string
  logs: AuditCorrelationStep[]
}

export interface AuditLogStats {
  total: number
  successCount: number
  failureCount: number
  highRiskCount: number
  unreadCount: number
  abnormalCount: number
  unprocessedAbnormalCount: number
  latestLog: AuditLogRecord | null
  dailyTrend: AuditLogDailyTrendItem[]
  moduleStats: AuditModuleStat[]
  operationStats: AuditOperationStat[]
  riskHeatmap: AuditHeatmapCell[]
  correlationChains: AuditCorrelationChain[]
  successRate: number
}

export interface CreateAuditLogPayload {
  module?: string
  operationType: string
  operationTime?: string
  operatorId?: string
  operatorAccount?: string
  operatorName?: string
  operatorRole?: string
  viewerScope?: string[]
  targetType?: string
  targetId?: string
  targetName?: string
  ipAddress?: string
  userAgent?: string
  location?: string
  beforeData?: Record<string, unknown> | null
  afterData?: Record<string, unknown> | null
  diffFields?: string[]
  resultStatus?: 'success' | 'failure'
  resultMessage?: string
  durationMs?: number
  riskLevel?: 'low' | 'medium' | 'high'
  riskReason?: string
  correlationId?: string
  chainId?: string
  tags?: string[]
  metadata?: Record<string, unknown> | null
  isRead?: boolean
  isAbnormal?: boolean
  alertChannels?: string[]
}

export interface AuditLogListParams extends PaginationParams {
  module?: string
  operationType?: string | string[]
  operatorKeyword?: string
  operatorRole?: string
  targetType?: string
  targetKeyword?: string
  resultStatus?: 'success' | 'failure' | 'all'
  riskLevel?: 'low' | 'medium' | 'high' | 'all'
  isRead?: 'true' | 'false'
  isAbnormal?: 'true' | 'false'
  chainId?: string
  correlationId?: string
  startTime?: string
  endTime?: string
  viewerRole?: string
  viewerId?: string
  viewerDepartments?: string
}

export interface AuditLogExportPayload {
  format: 'excel' | 'pdf'
  filters?: Partial<AuditLogListParams>
  viewerRole?: string
  viewerId?: string
  viewerDepartments?: string[] | string
  filename?: string
}

export interface AuditRule {
  _id: string
  name: string
  description?: string
  enabled: boolean
  targetType?: string
  operationTypes: string[]
  fields: string[]
  riskLevel: 'low' | 'medium' | 'high'
  threshold?: number
  timeWindowMinutes?: number
  triggerCount: number
  notifyChannels: string[]
  notifyEmails?: string[]
  extraConditions?: Record<string, unknown>
  createdAt: string
  updatedAt: string
}

// 用户 API
export const userAPI = {
  // 登录
  login: (params: LoginParams) => 
    request.post<LoginResponse>('/auth/login', params),

  // 注册
  register: (params: RegisterParams) => 
    request.post<User>('/auth/register', params),

  // 获取用户信息
  getUserInfo: () => 
    request.get<User>('/user/profile'),

  // 更新用户信息
  updateProfile: (data: Partial<User>) => 
    request.put<User>('/user/profile', data),

  // 修改密码
  changePassword: (data: { oldPassword: string; newPassword: string }) => 
    request.post('/user/change-password', data),

  // 上传头像
  uploadAvatar: (file: File, onProgress?: (progress: number) => void) => 
    request.upload<{ url: string }>('/user/avatar', file, {}, onProgress),

  // 登出
  logout: () => 
    request.post('/auth/logout'),

  // 刷新 token
  refreshToken: (refreshToken: string) => 
    request.post<{ token: string }>('/auth/refresh', { refreshToken }),

  // 获取平台用户列表（优先请求后端，失败时回退本地数据）
  getUsers: async (
    params?: Partial<{ page: number; pageSize: number; keyword: string; roleName: string }>
  ): Promise<ApiResponse<ManagedUserListResponse>> => {
    try {
      return await request.get<ManagedUserListResponse>(
        '/api/hzl/user/list',
        params,
        {
          headers: buildRoleHeaders(),
        }
      )
    } catch (error) {
      console.warn('获取用户列表失败，使用本地模拟数据回退', error)
      await asyncDelay(200)
      return {
        code: 200,
        success: true,
        message: 'OK',
        data: {
          list: mockManagedUsers,
          total: mockManagedUsers.length,
          page: 1,
          limit: mockManagedUsers.length,
          pageSize: mockManagedUsers.length,
          totalPages: 1,
        },
      }
    }
  },

  createUser: async (
    payload: {
      username: string
      password: string
      roleName?: string
      email?: string
      phone?: string
      department?: string
      status?: 'active' | 'invited' | 'suspended'
    }
  ): Promise<ApiResponse<ManagedUserDTO>> => {
    return request.post<ManagedUserDTO>('/api/hzl/user/add', payload, {
      headers: buildRoleHeaders(),
    })
  },

  // 更新用户角色、状态或风险等级（优先请求后端，失败时回退本地模拟）
  updateUser: async (
    id: string,
    payload: UpdateManagedUserPayload
  ): Promise<ApiResponse<ManagedUserDTO | null>> => {
    try {
      return await request.put<ManagedUserDTO>(
        `/api/hzl/users/${id}`,
        payload,
        {
          headers: buildRoleHeaders(),
        }
      )
    } catch (error) {
      console.warn('更新用户失败，使用本地模拟数据回退', error)
      await asyncDelay(200)
      const index = mockManagedUsers.findIndex((item) => item._id === id)
      if (index === -1) {
        return {
          code: 404,
          success: false,
          message: '用户不存在',
          data: null,
        }
      }

      mockManagedUsers[index] = {
        ...mockManagedUsers[index],
        ...payload,
        updatedAt: new Date().toISOString(),
      }

      return {
        code: 200,
        success: true,
        message: '更新成功',
        data: mockManagedUsers[index],
      }
    }
  },
}

// 文件夹类型 ✅ 新增
export interface Folder {
  _id: string
  name: string
  parentId: string | null
  path: string
  level: number
  description?: string
  color?: string
  icon?: string
  fileCount: number
  folderCount: number
  totalSize: number
  createdBy: string
  createdByName: string
  createdAt: string
  updatedAt: string
  isDeleted: boolean
  children?: Folder[]
}

// 文件管理 API 接口类型
export interface FileItem {
  _id: string
  filename: string
  storedName: string
  path: string
  url: string
  thumbnailUrl?: string  // 视频封面缩略图URL
  size: number
  sizeFormatted?: string
  mimetype: string
  extension: string
  category: 'image' | 'video' | 'audio' | 'document' | 'other'
  uploadedBy: string
  uploadedByName: string
  uploadedAt: string
  downloadCount: number
  viewCount: number
  isShared: boolean
  shareCode?: string
  shareExpireAt?: string
  sharePassword?: string
  shareDownloadLimit?: number
  shareDownloadCount?: number
  // 新增字段 ✅
  folderId?: string | null
  isFavorite?: boolean
  favoriteAt?: string
  isDeleted?: boolean
  deletedAt?: string
  deletedBy?: string
  daysInTrash?: number  // 回收站中的天数
}

export interface FileListParams extends PaginationParams {
  category?: string
  keyword?: string
  userId?: string
  folderId?: string | null  // 新增：按文件夹筛选
}

export interface FileListResponse {
  files: FileItem[]
  total: number
  page: number
  limit: number
  totalPages: number
}

export interface ShareConfig {
  expireDays?: number
  password?: string
  downloadLimit?: number
  permissions?: 'view' | 'edit'
}

export interface ShareResult {
  shareCode: string
  shareUrl: string
  expireAt: string
  hasPassword: boolean
}

// 文件 API
export const fileAPI = {
  // 上传单个文件
  uploadFile: (file: File, onProgress?: (progress: number) => void) => 
    request.upload<{ url: string; filename: string; size: number }>('/file/upload', file, {}, onProgress),

  // 批量上传文件
  uploadFiles: async (files: File[], onProgress?: (progress: number) => void) => {
    const formData = new FormData()
    files.forEach((file) => {
      formData.append(`files`, file)
    })
    return request.upload<{ files: Array<{ url: string; filename: string; size: number }> }>('/file/upload-batch', formData, {}, onProgress)
  },

  // 下载文件
  downloadFile: (url: string, filename?: string) => 
    request.download(url, filename),

  // 删除文件
  deleteFile: (fileId: string) => 
    request.delete(`/file/${fileId}`),
}

// 文件管理 API（完整版）
export const fileManagerAPI = {
  // 普通文件上传
  upload: (formData: FormData, onProgress?: (progress: number) => void) =>
    request.upload<FileItem[]>('http://localhost:3000/api/mqz/upload', formData, { showLoading: false }, onProgress),

  // 检查文件hash（秒传）
  checkHash: (hash: string) =>
    request.post<{ exists: boolean; data?: FileItem }>('http://localhost:3000/api/mqz/check-hash', { hash }, { showLoading: false }),

  // 查询已上传的分片列表（断点续传）
  checkChunks: (hash: string) =>
    request.get<{ uploadedChunks: number[]; uploadedCount: number }>(`http://localhost:3000/api/mqz/check-chunks/${hash}`, {}, { showLoading: false }),

  // 上传切片（使用 upload 方法以正确处理 FormData）
  uploadChunk: (formData: FormData) =>
    request.post<{ uploadedChunks: number; totalChunks: number }>('http://localhost:3000/api/mqz/upload-chunk', formData, { showLoading: false }),

  // 合并切片
  mergeChunks: (data: { hash: string; filename: string; totalChunks: number; size: number; userId?: string; userName?: string }) =>
    request.post<FileItem>('http://localhost:3000/api/mqz/merge-chunks', data, { showLoading: false }),

  // 获取文件列表
  getFiles: (params: FileListParams) =>
    request.get<FileListResponse>('http://localhost:3000/api/mqz/files', params),

  // 获取单个文件信息
  getFileById: (id: string) =>
    request.get<FileItem>(`http://localhost:3000/api/mqz/files/${id}`),

  // 删除文件
  deleteFile: (id: string) =>
    request.delete(`http://localhost:3000/api/mqz/files/${id}`),

  // 批量删除
  batchDelete: (ids: string[]) =>
    request.post('http://localhost:3000/api/mqz/files/batch-delete', { ids }),

  // 批量下载
  batchDownload: (ids: string[]) =>
    request.post<{ id: string; filename: string; url: string; size: number }[]>('http://localhost:3000/api/mqz/files/batch-download', { ids }),

  // 更新文件
  updateFile: (id: string, data: { filename?: string; description?: string; tags?: string[] }) =>
    request.put<FileItem>(`http://localhost:3000/api/mqz/files/${id}`, data),

  // 创建分享
  createShare: (id: string, config: ShareConfig) =>
    request.post<ShareResult>(`http://localhost:3000/api/mqz/share/${id}`, config),

  // 取消分享
  cancelShare: (id: string) =>
    request.post(`http://localhost:3000/api/mqz/unshare/${id}`),

  // 获取分享信息
  getShareInfo: (shareCode: string, password?: string) =>
    request.get<FileItem>(`http://localhost:3000/api/mqz/s/${shareCode}`, { password }),

  // 获取统计信息
  getStats: (userId?: string) =>
    request.get<{
      totalFiles: number
      totalSize: number
      totalSizeFormatted: string
      categoryCounts: Record<string, number>
      recentFiles: FileItem[]
    }>('http://localhost:3000/api/mqz/stats', { userId }),

  // 创建文件夹
  createFolder: (data: { name: string; parentId?: string | null; description?: string; color?: string; userId?: string; userName?: string }) =>
    request.post<Folder>('http://localhost:3000/api/mqz/folders', data),

  // 获取文件夹列表
  getFolders: (params?: { parentId?: string | null; userId?: string }) =>
    request.get<{ success: boolean; data: Folder[] }>('http://localhost:3000/api/mqz/folders', params),

  // 获取文件夹树
  getFolderTree: (userId?: string) =>
    request.get<{ success: boolean; data: Folder[] }>('http://localhost:3000/api/mqz/folders/tree', { userId }),

  // 更新文件夹
  updateFolder: (id: string, data: { name?: string; description?: string; color?: string; sortOrder?: number }) =>
    request.put<{ success: boolean; data: Folder }>(`http://localhost:3000/api/mqz/folders/${id}`, data),

  // 删除文件夹
  deleteFolder: (id: string, userId?: string) =>
    request.delete(`http://localhost:3000/api/mqz/folders/${id}`, { data: { userId } }),

  // 移动文件
  moveFile: (id: string, folderId: string | null) =>
    request.post(`http://localhost:3000/api/mqz/files/${id}/move`, { folderId }),

  // 收藏文件
  favoriteFile: (id: string) =>
    request.post(`http://localhost:3000/api/mqz/files/${id}/favorite`),

  // 取消收藏
  unfavoriteFile: (id: string) =>
    request.delete(`http://localhost:3000/api/mqz/files/${id}/favorite`),

  // 获取收藏列表
  getFavorites: (params?: { page?: number; limit?: number; category?: string; userId?: string }) =>
    request.get<FileListResponse>('http://localhost:3000/api/mqz/favorites', params),

  // 移入回收站
  moveToTrash: (id: string, userId?: string) =>
    request.post(`http://localhost:3000/api/mqz/files/${id}/trash`, { userId }),

  // 还原文件
  restoreFile: (id: string) =>
    request.post(`http://localhost:3000/api/mqz/files/${id}/restore`),

  // 获取回收站文件
  getTrashFiles: (params?: { page?: number; limit?: number; userId?: string }) =>
    request.get<FileListResponse>('http://localhost:3000/api/mqz/trash', params),

  // 永久删除
  permanentDelete: (id: string) =>
    request.delete(`http://localhost:3000/api/mqz/files/${id}/permanent`),

  // 清空回收站
  clearTrash: (userId?: string) =>
    request.post('http://localhost:3000/api/mqz/trash/clear', { userId }),

  // 自动清理过期文件
  autoCleanTrash: () =>
    request.post('http://localhost:3000/api/mqz/trash/auto-clean'),

  // 更新文件信息（用于更新封面URL）
  updateFileCover: (fileId: string, data: Partial<FileItem>) =>
    request.put<FileItem>(`http://localhost:3000/api/mqz/files/${fileId}`, data, { showLoading: false }),

}

// 权限管理相关接口类型
export interface Permission {
  id: number
  roleName: string        // 角色名称
  permissionScope: string // 权限范围
  applicableScene: string // 适用场景
  createTime: string      // 创建时间
  updateTime: string      // 更新时间
}

// 权限管理 API
export const permissionAPI = {
  // 获取权限列表
  getList: (params?: { page?: number; pageSize?: number; roleName?: string }) => 
    request.get<{ list: Permission[]; total: number; page: number; pageSize: number }>('/api/hzl/quan/list', params),

  // 获取所有权限
  getAll: () => 
    request.get<Permission[]>('/api/hzl/quan/all'),

  // 添加权限
  add: (data: Omit<Permission, 'id' | 'createTime' | 'updateTime'>) => 
    request.post<Permission>('/api/hzl/quan/add', data),

  // 更新权限
  update: (id: number, data: Omit<Permission, 'id' | 'createTime' | 'updateTime'>) => 
    request.put<Permission>(`/api/hzl/quan/update/${id}`, data),

  // 删除权限
  delete: (id: number) => 
    request.delete(`/api/hzl/quan/delete/${id}`),

  // 批量删除权限
  batchDelete: (ids: number[]) => 
    request.post('/api/hzl/quan/batchDelete', { ids }),
}

// 通用 CRUD API 工厂函数
export function createCrudAPI<T extends { id: number | string }>(basePath: string) {
  return {
    // 获取列表
    getList: (params?: PaginationParams & Record<string, unknown>) => 
      request.get<PaginationResponse<T>>(`${basePath}`, params),

    // 获取详情
    getById: (id: number | string) => 
      request.get<T>(`${basePath}/${id}`),

    // 创建
    create: (data: Omit<T, 'id'>) => 
      request.post<T>(`${basePath}`, data),

    // 更新
    update: (id: number | string, data: Partial<T>) => 
      request.put<T>(`${basePath}/${id}`, data),

    // 删除
    delete: (id: number | string) => 
      request.delete(`${basePath}/${id}`),

    // 批量删除
    batchDelete: (ids: (number | string)[]) => 
      request.post(`${basePath}/batch-delete`, { ids }),
  }
}

// 示例：创建文章 API
export interface Article {
  id: number
  title: string
  content: string
  summary?: string
  author: string
  status: 'draft' | 'published' | 'archived'
  tags: string[]
  createdAt: string
  updatedAt: string
}

export const articleAPI = {
  ...createCrudAPI<Article>('/articles'),
  
  // 发布文章
  publish: (id: number) => 
    request.post(`/articles/${id}/publish`),

  // 归档文章
  archive: (id: number) => 
    request.post(`/articles/${id}/archive`),

  // 获取热门文章
  getHotArticles: (limit = 10) => 
    request.get<Article[]>('/articles/hot', { limit }),
}

// 文档相关接口类型
export interface DocumentNode {
  id: string
  name: string
  type: 'folder' | 'document'
  parentId: string | null
  children?: DocumentNode[]
  content?: string // 文档内容（仅文档类型有）
  // 新增：文档细分类型（用于模板和类别区分，如 product-detail、campaign-plan、sheet 等）
  docType?: string
  // 新增：若基于模板创建，可记录模板键
  templateKey?: string
  createdAt: string
  updatedAt: string
  author?: string
  size?: number // 文档大小（字节）
  isFavorite?: boolean
  tags?: string[]
  deletedAt?: string // 删除时间（如果存在则表示已删除）
  lastAccessedAt?: string // 最后访问时间
}

export interface CreateDocumentParams {
  name: string
  type: 'folder' | 'document'
  parentId: string | null
  content?: string
  // 新增：文档细分类型与模板键（仅当 type 为 document 时有效）
  docType?: string
  templateKey?: string
}

export interface UpdateDocumentParams {
  name?: string
  content?: string
  parentId?: string | null
  docType?: string
}

// ============== 模板接口类型 ==============
export interface DocTemplateDTO {
  _id: string
  key: string
  name: string
  docType: string
  defaultName: string
  content: string
  enabled: boolean
  createdAt: string
  updatedAt: string
}

export interface CreateTemplateParams {
  key: string
  name: string
  docType: string
  defaultName: string
  content: string
  enabled?: boolean
}

export type UpdateTemplateParams = Partial<CreateTemplateParams>;

// 历史版本接口
export interface HistoryVersion {
  id: string
  version: number
  user: string
  timestamp: number
  content: string
  description: string
}

// 评论接口
export interface Comment {
  id: string
  user: string
  avatar: string
  color: string
  content: string
  timestamp: number
  position?: number
  replies?: Comment[]
  isEditable?: boolean
}

// 在线用户接口
export interface OnlineUser {
  id: string
  userId?: string
  sessionId?: string | null
  name: string
  avatar: string
  color: string
  cursorPosition?: number
}

// 文档相关API
export const documentAPI = {
  // 获取文档树
  getDocumentTree: () => request.get<DocumentNode[]>('/api/documents/tree'),
  
  // 获取文档内容
  getDocument: (id: string) => request.get<DocumentNode>(`/api/documents/${id}`),
  
  // 获取文档内容（带响应包装）
  getDocumentById: (id: string) => request.get<{ success: boolean; data: DocumentNode }>(`/api/documents/${id}`),
  
  // 创建文档
  createDocument: (params: CreateDocumentParams) => request.post<DocumentNode>('/api/documents', params),
  
  // 更新文档
  updateDocument: (id: string, params: UpdateDocumentParams) => request.put<DocumentNode>(`/api/documents/${id}`, params),
  
  // 删除文档
  deleteDocument: (id: string) => request.delete<{success: boolean}>(`/api/documents/${id}`),
  
  // 批量删除文档
  batchDeleteDocuments: (ids: string[]) => request.post<{success: boolean}>('/api/documents/batch-delete', { ids }),
  
  // 移动文档
  moveDocument: (id: string, newParentId: string) => request.post<DocumentNode>(`/api/documents/${id}/move`, { newParentId }),
  
  // 清空所有文档（用于测试）
  purgeDocuments: () => request.delete<{success: boolean}>('/api/documents/purge'),
  
  // 获取文档历史版本
  getDocumentVersions: (id: string) => request.get<{ success: boolean; data: HistoryVersion[] }>(`/api/documents/${id}/versions`),
  
  // 创建版本
  createVersion: (id: string, data: { content: string; user: string; description?: string }) => 
    request.post<{ success: boolean; data: HistoryVersion }>(`/api/documents/${id}/versions`, data),

  // 恢复到指定版本
  restoreVersion: (id: string, versionId: string) =>
    request.post<{ success: boolean; data: { content: string } }>(`/api/documents/${id}/versions/${versionId}/restore`),
  
  // 获取文档评论
  getDocumentComments: (id: string) => request.get<{ success: boolean; data: Comment[] }>(`/api/documents/${id}/comments`),
  
  // 创建评论
  createComment: (id: string, data: { user: string; avatar: string; color: string; content: string; position?: number; parentId?: string }) => 
    request.post<{ success: boolean; data: Comment }>(`/api/documents/${id}/comments`, data),

  // 更新评论
  updateComment: (id: string, commentId: string, data: { content: string }) =>
    request.put<{ success: boolean; data: Comment }>(`/api/documents/${id}/comments/${commentId}`, data),

  // 删除评论
  deleteComment: (id: string, commentId: string) =>
    request.delete<{ success: boolean }>(`/api/documents/${id}/comments/${commentId}`),
  
  // 获取在线用户
  getOnlineUsers: (id: string) => request.get<{ success: boolean; data: OnlineUser[] }>(`/api/documents/${id}/online-users`),
  
  // 更新在线用户状态
  updateOnlineUser: (id: string, data: { userId: string; sessionId?: string | null; userName: string; avatar: string; color: string; cursorPosition?: number }) => 
    request.post(`/api/documents/${id}/online-users`, data),
  
  
  // ========== 标签相关 ==========
  // 获取所有标签
  getAllTags: () => request.get<Array<{id: string; name: string}>>('/api/documents/tags/all'),
  
  // 批量添加标签
  batchAddTags: (ids: string[], tags: string[]) => request.post<{success: boolean}>('/api/documents/batch-add-tags', { ids, tags }),
  
  // ========== 批量操作 ==========
  // 批量移动
  batchMoveDocuments: (ids: string[], targetId: string) => request.post<{success: boolean}>('/api/documents/batch-move', { ids, targetId }),
  
  // 批量复制
  batchCopyDocuments: (ids: string[], targetId: string) => request.post<DocumentNode[]>('/api/documents/batch-copy', { ids, targetId }),
  
  // 批量重命名
  batchRenameDocuments: (ids: string[], params: { prefix: string; startNumber: number }) => 
    request.post<{success: boolean}>('/api/documents/batch-rename', { ids, ...params }),
  
  // ========== 分享相关 ==========
  // 分享文档
  shareDocument: (id: string, config: ShareConfig) => request.post<{
    shareCode: string;
    shareUrl: string;
    expireAt: string | null;
  }>(`/api/documents/${id}/share`, config),
  
  // 取消分享
  cancelShare: (id: string) => request.post<{success: boolean}>(`/api/documents/${id}/cancel-share`),
  
  // ========== 上传 ==========
  // 上传文档
  uploadDocument: (formData: FormData) => {
    return request.post<DocumentNode>('/api/documents/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
  
  // ========== 排序 ==========
  // 拖放排序
  reorderDocument: (id: string, targetId: string) => request.post<DocumentNode>(`/api/documents/${id}/reorder`, { targetId }),
  
  // ========== 导出 ==========
  // 批量导出
  exportDocuments: async (ids: string[]) => {
    const response = await request.post<unknown>('/api/documents/batch-export', { ids });
    // 后端返回 JSON，需要转换为 Blob
    const jsonStr = JSON.stringify(response.data);
    return new Blob([jsonStr], { type: 'application/json' });
  },
};

// 模板相关API
export const templateAPI = {
  // 获取模板列表
  list: () => request.get<DocTemplateDTO[]>('/api/template/list'),
  
  // 获取模板详情
  get: (id: string) => request.get<DocTemplateDTO>(`/api/template/${id}`),
  
  // 创建模板
  create: (data: CreateTemplateParams) => request.post<DocTemplateDTO>('/api/template', data),
  
  // 更新模板
  update: (id: string, data: UpdateTemplateParams) => request.put<DocTemplateDTO>(`/api/template/${id}`, data),
  
  // 删除模板
  delete: (id: string) => request.delete<{success: boolean}>(`/api/template/${id}`),
};

// 文档协同相关API
export const documentCollabAPI = {
  // 获取在线用户列表
  getOnlineUsers: (documentId: string) => request.get<OnlineUser[]>('/api/document/collab/users', { params: { documentId } }),
  
  // 获取编辑历史
  getEditHistory: (documentId: string) => request.get<HistoryVersion[]>('/api/document/collab/history', { params: { documentId } }),
};
// 仪表板相关接口类型
export interface RealTimeData {
  sales: number
  orders: number
  users: number
  products: number
  conversionRate: number
  avgOrderValue: number
  stockAlerts: number
  returnRate: number
  totalSales?: number
  totalOrders?: number
  salesTrend?: number
  ordersTrend?: number
}

export interface SalesTrendItem {
  date: string
  sales: number
  orders: number
  [key: string]: string | number
}

export interface CategorySalesItem {
  name: string
  sales: number
  orders: number
  [key: string]: string | number
}

export interface SalesPieItem {
  name: string
  value: number
  color: string
  [key: string]: string | number
}

export interface OrderDetailItem {
  id: string
  product: string
  user: string
  region: string
  amount: number
  time: string
}

export interface DataComparisonItem {
  label: string
  currentValue: number
  previousValue: number
  unit: string
  previousLabel?: string
  growthRate?: number
  metric?: string
}

export interface BusinessModuleDataItem {
  name: string
  value: number
  color: string
}

export interface BusinessModuleDataResponse {
  data: BusinessModuleDataItem[]
  monthOnMonth: number
  yearOnYear: number
}

export type ChatMessageType = 'text' | 'image' | 'video' | 'audio' | 'file'

export interface ChatMessageMetadata {
  duration?: number
  size?: number
  fileName?: string
  width?: number
  height?: number
  mimeType?: string
  extra?: Record<string, unknown>
}

export interface ChatMessage {
  id: string
  roomId: string
  senderId: string
  senderName?: string
  senderAvatar?: string
  type: ChatMessageType
  content: string
  metadata?: ChatMessageMetadata
  mentions?: string[]
  readBy?: string[]
  revoked?: boolean
  createdAt: string
  updatedAt?: string
}

export interface ChatRoomSummary {
  messageId?: string
  preview?: string
  type?: ChatMessageType
  senderId?: string
  senderName?: string
  createdAt?: string
}

export interface ChatRoom {
  id: string
  name: string
  avatar?: string
  description?: string
  type: 'group' | 'private'
  members: string[]
  isDefault?: boolean
  metadata?: Record<string, unknown>
  lastMessage?: ChatRoomSummary | null
  unread?: number
  createdAt?: string
  updatedAt?: string
}

export interface ChatPresenceUser {
  userId: string
  username?: string
  avatar?: string
  lastActive?: number
}

// 看板数据 API
export const dashboardAPI = {
  // 获取实时数据
  getRealTimeData: () =>
    request.get<RealTimeData>('http://localhost:3000/api/hwb/realtime'),

  // 获取销售趋势
  getSalesTrend: (days?: number) =>
    request.get<SalesTrendItem[]>('http://localhost:3000/api/hwb/sales-trend', { days }),

  // 获取类别销售
  getCategorySales: (days?: number) =>
    request.get<CategorySalesItem[]>('http://localhost:3000/api/hwb/category-sales', { days }),

  // 获取销售占比
  getSalesPie: (days?: number) =>
    request.get<SalesPieItem[]>('http://localhost:3000/api/hwb/sales-pie', { days }),

  // 获取订单详情
  getOrderDetails: (limit?: number) =>
    request.get<OrderDetailItem[]>('http://localhost:3000/api/hwb/order-details', { limit }),

  // 获取对比数据
  getComparison: (days?: number) =>
    request.get<DataComparisonItem[]>('http://localhost:3000/api/hwb/comparison', { days }),

  // 获取业务模块数据
  getBusinessModuleData: () =>
    request.get<BusinessModuleDataResponse>('http://localhost:3000/api/hwb/business-module-data'),

  // 保存实时数据
  saveRealTimeData: (data: Partial<RealTimeData>) =>
    request.post('http://localhost:3000/api/hwb/realtime', data),

  // 保存销售趋势
  saveSalesTrend: (data: SalesTrendItem) =>
    request.post('http://localhost:3000/api/hwb/sales-trend', data),

  // 保存类别销售
  saveCategorySales: (data: CategorySalesItem) =>
    request.post('http://localhost:3000/api/hwb/category-sales', data),

  // 保存订单详情
  saveOrderDetail: (data: Omit<OrderDetailItem, 'id'>) =>
    request.post('http://localhost:3000/api/hwb/order-details', data),

  // 保存对比数据
  saveComparison: (data: DataComparisonItem) =>
    request.post('http://localhost:3000/api/hwb/comparison', data),

  // 保存业务模块数据
  saveBusinessModuleData: (data: { moduleName: string; value: number; color: string; monthOnMonth?: number; yearOnYear?: number; description?: string }) =>
    request.post('http://localhost:3000/api/hwb/business-module-data', data),
}

export const chatAPI = {
  listRooms: (userId: string) => request.get<ChatRoom[]>('/api/chat/rooms', { userId }),
  createRoom: (payload: { name: string; members: string[]; avatar?: string; description?: string; creatorId?: string }) =>
    request.post<ChatRoom>('/api/chat/rooms', payload),
  ensurePrivateRoom: (payload: { userId: string; targetId: string }) =>
    request.post<ChatRoom>('/api/chat/private-room', payload),
  updateRoom: (roomId: string, payload: { name?: string; description?: string; avatar?: string }) =>
    request.put<ChatRoom>(`/api/chat/rooms/${roomId}`, payload),
  fetchMessages: (params: { roomId: string; before?: string; limit?: number }) =>
    request.get<ChatMessage[]>('/api/chat/messages', params),
  markRead: (payload: { roomId: string; userId: string; messageIds: string[] }) =>
    request.post('/api/chat/read', payload),
  clearMessages: (roomId: string) => request.delete('/api/chat/messages', { data: { roomId } }),
}

export const auditLogAPI = {
  getList: (params?: AuditLogListParams) => request.get<AuditLogListResponse>('/api/hzl/audit-logs', params),
  getStats: (params?: Partial<AuditLogListParams>) => request.get<AuditLogStats>('/api/hzl/audit-logs/stats', params),
  create: (payload: CreateAuditLogPayload) => request.post<AuditLogRecord>('/api/hzl/audit-logs', payload, { showError: false }),
  markRead: (payload: { ids: string[]; isRead?: boolean; acknowledgedBy?: string }) =>
    request.post('/api/hzl/audit-logs/batch/mark-read', payload),
  export: (payload: AuditLogExportPayload) =>
    request.postBinary(
      '/api/hzl/audit-logs/export',
      {
        ...payload,
        filename: undefined,
        viewerDepartments: Array.isArray(payload.viewerDepartments)
          ? payload.viewerDepartments
          : payload.viewerDepartments,
      },
      payload.filename || `audit-logs-${new Date().toISOString().slice(0, 10)}.${payload.format === 'pdf' ? 'pdf' : 'xlsx'}`
    ),
  getRules: () => request.get<AuditRule[]>('/api/hzl/audit-logs/rules'),
  createRule: (data: Partial<AuditRule>) => request.post<AuditRule>('/api/hzl/audit-logs/rules', data),
  updateRule: (id: string, data: Partial<AuditRule>) => request.put<AuditRule>(`/api/hzl/audit-logs/rules/${id}`, data),
  deleteRule: (id: string) => request.delete(`/api/hzl/audit-logs/rules/${id}`),
}

// 导出所有 API
export default {
  user: userAPI,
  file: fileAPI,
  fileManager: fileManagerAPI,
  article: articleAPI,
  permission: permissionAPI,
  dashboard: dashboardAPI,
  chat: chatAPI,
  auditLog: auditLogAPI,
}
